package com.csii.core.dict;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.csii.core.constant.SyncDictType;
import com.csii.core.dict.handler.RedisDictGetHandler;
import com.csii.core.system.vo.DictRedisHash;
import com.csii.galaxy.studio.service.GalaxyStudioBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.List;
import java.util.stream.Collectors;


//@Component
public class DictPublishService {
    @Autowired
    private GalaxyStudioBaseService galaxyStudioBaseService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    private RedisDictGetHandler redisDictGetHandler;

    private final String IS_DICT_SERVICE_KEY = "IS_DICT_SERVICE";

    private String SYNC_DICT_PREFIX = "SYNC_DICT_PREFIX_";

    private String DICT_SYNC_KEY = "DICT_SYNC_KEY_";

    private final String DICT_REGISTER_LIST = "DICT_REGISTER_LIST";

    @Value("${spring.name}")
    private String appName;

    @Value("${dict.isService:false}")
    private boolean isDictService;


    private  final String PUBLISH_LUA="local value=ARGV[1]; for i,k in ipairs(KEYS) do redis.call('lpush',k,value) end return 1 ";

    public void addDictDataToRedis(String hKey ,String key ,String value){
        publishDictDataToRedis(hKey,key,value,SyncDictType.OPERATION_SET);
    }


    private void publishDictDataToRedis(String hKey ,String key ,String value,String operationType){
        DictRedisHash dictRedisHash = new DictRedisHash();
        dictRedisHash.setDictCode(hKey);
        dictRedisHash.setItemText(key);
        dictRedisHash.setItemValue(value);
        dictRedisHash.setOperationType(operationType);
        String jsonValue = JSONUtil.toJsonStr(dictRedisHash);
        List<Object> range = redisTemplate.opsForList().range(DICT_REGISTER_LIST, 0, -1);
        List<String> keys = range.stream().filter(v -> ((String) v).startsWith(key)).map(v -> (String) v).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(keys)){
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(PUBLISH_LUA,Long.class);
            redisTemplate.execute(redisScript, keys,jsonValue);
        }
    }

    public void delRedisDictData(String hKey,String key){
        publishDictDataToRedis(hKey,key,null,SyncDictType.OPERATION_DEL);
    }

}
